package com.heima.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.exception.CustException;
import com.heima.feigns.ApAuthorFeign;
import com.heima.feigns.WemediaFeign;
import com.heima.model.article.pojos.ApAuthor;
import com.heima.model.common.constants.admin.AdminConstants;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.media.pojos.WmUser;
import com.heima.model.user.dtos.AuthDTO;
import com.heima.model.user.pojos.ApUser;
import com.heima.model.user.pojos.ApUserRealname;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.mapper.ApUserRealnameMapper;
import com.heima.user.service.ApUserRealnameService;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class ApUserRealnameServiceImpl extends ServiceImpl<ApUserRealnameMapper, ApUserRealname> implements ApUserRealnameService {
    @Autowired
    private ApUserRealnameMapper apUserRealnameMapper;
    @Autowired
    private ApAuthorFeign apAuthorFeign;
    @Autowired
    private WemediaFeign wmUserFeign;
    @Autowired
    private ApUserMapper apUserMapper;

    //app端用户认证列表查询
    @Override
    public ResponseResult loadListByStatus(AuthDTO dto) {
        //非空判断
        if (dto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //有参数,分页查询该用户认证状态
        //创建分页对象
        Page<ApUserRealname> page = new Page<>(dto.getPage(), dto.getSize());
        //创建wrapper
        LambdaQueryWrapper<ApUserRealname> wrapper = Wrappers.lambdaQuery();
        //判断是否有id
        if (dto.getId() != null && dto.getId().toString().trim()!="") {
            wrapper.eq(ApUserRealname::getId, dto.getId());
        }
        //判断是否有status
        if (dto.getStatus() != null) {
            wrapper.eq(ApUserRealname::getStatus, dto.getStatus());
        }
        IPage<ApUserRealname> apUserRealnameIPage = apUserRealnameMapper.selectPage(page, wrapper);
        //非空判断
        if (apUserRealnameIPage == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.AP_USER_DATA_NOT_EXIST);
        }
        //存在数据 封装数据并返回
        return new PageResponseResult(dto.getPage(), dto.getSize(), apUserRealnameIPage.getTotal(), apUserRealnameIPage.getRecords());
    }

    //实名认证审核
    @Override
    @GlobalTransactional(rollbackFor = Exception.class)
//    @Transactional
    public ResponseResult updateStatusById(AuthDTO dto, Short passAuth) {
        //非空判断
        if (dto.getId() == null) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }
        //根据id查询认证列表
        ApUserRealname apUserRealname = apUserRealnameMapper.selectById(dto.getId());
        if (apUserRealname == null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //根据用户id查询用户  判断是否存在
        ApUser apUser = apUserMapper.selectById(apUserRealname.getUserId());
        //判断
        if (apUser == null) {
            //不存在该用户
            CustException.cust(AppHttpCodeEnum.DATA_EXIST, "不存在该用户!");
        }
        //判断是否处于待审核状态
        if (apUserRealname.getStatus() != 1) {
            CustException.cust(AppHttpCodeEnum.DATA_EXIST, "当前用户未处于待审核状态!");
        }
        //根据user_id查询author是否存在
        ResponseResult<ApAuthor> byUserId1 = apAuthorFeign.findByUserId(dto.getId());
        if (byUserId1.getData() != null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_EXIST, "该作者已经存在!");
        }
        //根据用户名查询wemedia是否存在
        ResponseResult<WmUser> byName1 = wmUserFeign.findByName(apUser.getName());
        if (byName1.getData() != null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_EXIST, "该自媒体用户已经存在!");
        }
        //修改ap_user_realname表的用户状态
        apUserRealname.setStatus(passAuth);
        //修改数据
        apUserRealnameMapper.updateById(apUserRealname);
        //判断passAuth
        if (AdminConstants.PASS_AUTH.equals(passAuth)) {
            //根据名字查询自媒体用户信息是否存在
            ResponseResult<WmUser> byName = wmUserFeign.findByName(apUser.getName());
            //判断响应状态码
            if (byName.getData() != null) {
                CustException.cust(AppHttpCodeEnum.SERVER_ERROR);
            }
            WmUser wmUser2 = byName.getData();
            //判断是否存在
            if (wmUser2 != null) {
                CustException.cust(AppHttpCodeEnum.SERVER_ERROR);
            }
            //根据id查询作者信息是否存在
            ResponseResult<ApAuthor> byUserId = apAuthorFeign.findByUserId(apUser.getId());
            //判断响应状态码
            if (byUserId.getData() != null) {
                CustException.cust(AppHttpCodeEnum.SERVER_ERROR);
            }
            ApAuthor apAuthor2 = byUserId.getData();
            //判断是否存在
            if (apAuthor2 != null) {
                CustException.cust(AppHttpCodeEnum.DATA_EXIST, "作者已经存在!");
            }
            //审核成功,创建自媒体账户和作者  账号的用户名和密码与app一致
            //调用feign接口新增自媒体用户
            WmUser wmUser = new WmUser();
            wmUser.setApUserId(apUser.getId());
            wmUser.setName(apUser.getName());
            wmUser.setPassword(apUser.getPassword());
            wmUser.setSalt(apUser.getSalt());
            wmUser.setNickname(apUserRealname.getName());
            wmUser.setPhone(apUser.getPhone());
            wmUser.setStatus(1);
            wmUser.setCreatedTime(new Date());
            ResponseResult<WmUser> saveWmUser = wmUserFeign.save(wmUser);
            //调用feign接口新增文章作者
            ApAuthor apAuthor = new ApAuthor();
            apAuthor.setName(apUser.getName());
            apAuthor.setUserId(apUserRealname.getUserId());
            apAuthor.setCreatedTime(new Date());
            apAuthor.setType(AdminConstants.AUTHOR_TYPE);
            //添加
            apAuthorFeign.save(apAuthor);
//            int a = 1 / 0;  //测试异常
            //根据user_id查询author,获取author_user_id
            ResponseResult<ApAuthor> byUserId2 = apAuthorFeign.findByUserId(dto.getId());
            ApAuthor apAuthor3 = byUserId2.getData();
            Integer author_id = byUserId2.getData().getId();  //作者id
            ResponseResult<WmUser> byName2 = wmUserFeign.findByName(apUser.getName());
            WmUser wemedia = byName2.getData();
            Integer wemedia_id = wemedia.getId();  //自媒体id
            //将自媒体id放到author
//            apAuthor3.setWmUserId(wemedia_id);
            apAuthor3.setWmUserId(saveWmUser.getData().getId());
            //修改回数据库
            apAuthorFeign.save(apAuthor3);
            //返回结果
            return ResponseResult.okResult();
        }
        //修改ap_user_realname表的用户状态
        apUserRealname.setStatus(passAuth);
        //审核失败修改数据
        apUserRealnameMapper.updateById(apUserRealname);
//        CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "认证请求不存在!");
        return ResponseResult.okResult();
    }
}